<?php
//---------------------------------------------------------------------------------------
// Author  : BugTraker
// File    : comment.php - module responsible for displaying/adding/removing comments.
// Date    : 08/01/2010 23:34
// Website : http://www.bugtraker.pl 
//
// SAC (Simple Add Comment) - Copyright (C) 2009 BugTraker (http://www.bugtraker.pl).
//
// SAC is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// BeFree is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with BeFree; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//---------------------------------------------------------------------------------------


require ('config.php');
require ('connection.php');
require_once ('recaptcha-php-1.10/recaptchalib.php');


//---------------------------------------------------------------------------------------
// Display given number of last comments.
//
// Arguments:
// $num_last_records - number of last records to be displayed
// 
// Return:
// N/A
//---------------------------------------------------------------------------------------
function sac_comment_display($num_last_records)
{
  sac_connection_open();                                                                  // Open connection to db.
  $query = sprintf("SELECT * FROM comments ORDER BY id DESC LIMIT %d", $num_last_records);// Form query to display last 'n' records.
  $result = mysql_query($query);
  if (!$result)                                                                           // Check for failure.
    {
      die(mysql_error());                                                                 // Display reason of failure.
    }
  else
    {    
      while ($row = mysql_fetch_assoc($result))                                           // Printout 'n' records. 
        {
          echo strip_tags(stripslashes(sprintf("Author: %s Date %s", $row['user_name'], $row['date'])));
          echo "<br /><br />";
          echo strip_tags(stripslashes($row['cmt']));
          echo "<br /><br /><br /><br />";
        }
    }
  sac_connection_close();                                                                 // Close db connection.
}


//---------------------------------------------------------------------------------------
// Add user comment. Gets data from form: comment, author, validation code and stores
// them in db.
//
// Arguments:
// N/A
//
// Return:
// N/A
//---------------------------------------------------------------------------------------
function sac_comment_add()
{
  if (!empty($_POST['submit']) && !empty($_POST['comment']) && !empty($_POST['author']) &&// Check if 
      FALSE == strstr($_POST['comment'], "Write your comment...") &&                      // Check if default phrases are changed.
      FALSE == strstr($_POST['author'], "Author"))
    {
      $resp = recaptcha_check_answer (SAC_RECAPTCHA_PRIVATEKEY,
                                      $_SERVER["REMOTE_ADDR"],
                                      $_POST["recaptcha_challenge_field"],
                                      $_POST["recaptcha_response_field"]);

      if (TRUE == $resp->is_valid)
        {
          sac_connection_open();                                                          // Open db connection.
          if ((FALSE == sac_spam_check($_POST['comment'])) && (FALSE == sac_spam_check($_POST['author'])))
            {
              $query = sprintf("INSERT INTO comments (cmt, user_name) VALUES ('%s', '%s')", 
                               mysql_real_escape_string($_POST['comment']), 
                               mysql_real_escape_string($_POST['author']));
              $result = mysql_query($query);
              if (!$result)                                                               // Check if query did not succeed.
                {
                  echo "<b>SQL connection closed - reason: ".mysql_error()."."; 
                  echo "<br />SQL query:".$query." <br /></b>"; 
                }
              else
                {
                  sac_leave_recent_records(SAC_NUM_REC_TO_KEEP);
                  echo "<b>Your comment has been added.</b>";
                }
            }
          else
            {
              echo "<b>No place for spam here.</b>";
            }
          sac_connection_close();                                                         // Close db connection.
        }
      else
       {
         echo "<b>Captcha error:</b>".$resp->error;                                       // Code from form does not match session code.
       }
    }
  else
    {
      if (!empty($_POST['submit']))                                                       // Submit has been pressed but some fields were empty.
        {
          sac_display_incorrect_fields();
        }
      sac_display_form();                                                                 // Display html form.
    }
}


//---------------------------------------------------------------------------------------
// Display HTML form.
// Session random code is generated which must be then validated by user in order
// to accept form.
//
// Arguments:
// N/A
//
// Return:
// N/A
//---------------------------------------------------------------------------------------
function sac_display_form()
{
php?>

<form name="add_comment" method="post" action="" />
Name:
<br />
<input type="text" name="author" value="Author" onClick="document.add_comment.author.value=''; " />
<br />
<br />
Comment:
<br />
<textarea name="comment" rows="5" cols="50" wrap="physical" onClick="document.add_comment.comment.value=''; " />
Write your comment...
</textarea>
<br />
<?php
echo recaptcha_get_html(SAC_RECAPTCHA_PUBLICKEY);
php?>

<input type="submit" name="submit" value="Submit" />
</form>
  
<?php
}


//---------------------------------------------------------------------------------------
// Spam check. Function looks for links, bad words and garbage comments.
//
// Arguments:
// N/A
//
// Return:
// N/A
//---------------------------------------------------------------------------------------
function sac_spam_check($string)
{
  $ret = FALSE;


  $spam_strings = array("http", "www", "porn", "sex");                                    // Expand this array if you require more protection.
  reset($spam_strings);
  foreach ($spam_strings as $spam_word)
    {
      if (FALSE != stristr($string, $spam_word))                                          // Check if word from spam list has been found.
        {
          $ret = TRUE;
          break;
        }
    }

  return ($ret);
}


//---------------------------------------------------------------------------------------
// Display fileds that has not been filled in.
// 
// Arguments:
// N/A
//
// Return:
// N/A
//---------------------------------------------------------------------------------------
function sac_display_incorrect_fields()
{
  if (FALSE != strstr($_POST['comment'], "Write your comment...") ||                      // Check if author/comment fields were left defaulted.
      FALSE != strstr($_POST['author'], "Author"))
    {
      echo "<b>Author and/or comment fields must be filled in (defaults found).</b>"; 
    }
  else
    {
      $note  = "<b>Following sections must be filled in:";
      $count = 0;
      if (empty($_POST['author']))                                                        // Check for author.
        {
          $note .= " name";
          $count++;
        }
      if (empty($_POST['comment']))                                                       // Check for comment.
        {
          if ($count > 0)
            {
              $note .= ",";
            }
          $note .= " comment";
          $count++;
        }
      $note .= ".</b>";
      echo $note;
    }
}


//---------------------------------------------------------------------------------------
// Leaves only last N records.
// 
// Arguments:
// N/A
//
// Return:
// N/A
//---------------------------------------------------------------------------------------
function sac_leave_recent_records($num_records)
{
  $query = sprintf("DELETE FROM comments
                    WHERE id NOT IN (
                      SELECT id
                      FROM (
                        SELECT id
                        FROM comments
                        ORDER BY id DESC
                        LIMIT %d
                      ) select_most_recent
                    )", $num_records);

  $result = @mysql_query($query);

  if (!$result)
    {
      echo "Error :".mysql_error()." ";
    }
}

php?>

